<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>13-漂浮小广告</title>
	<style>
		*{
			margin: 0;
			padding: 0;
		}
	   #box{
		   width: 200px;
		   height: 283px;
		   border: 1px solid red;
		   background:url(images/abcd.png);
		   background-repeat: no-repeat;
		   position: absolute;
		   left: 0;
		   top: 0;
		   border-radius:6px;
	   }
		#close{
			font-size: 30px;
			color: red;
			cursor: pointer;
			position: absolute;
			right:0;
			top:3px;
		}
	</style>
</head>
<body>
      <div id="box">
          <div id="close">X</div>
      </div>
	  <script type="text/javascript">
		//思路：让广告动起来，需要改变的是定位的left,top
		//1.抓取元素对象
		var box = document.querySelector('#box');
		var closeBtn = document.querySelector('#close');
		//计算box的最大Left和top值
		var maxLeft = document.documentElement.clientWidth-box.offsetWidth;
		var maxTop = document.documentElement.clientHeight-box.offsetHeight;
		console.log(maxLeft+'==1='+maxTop);
		//窗口的重置
		window.addEventListener('resize',function(e){
			maxLeft = document.documentElement.clientWidth-box.offsetWidth;
			maxTop = document.documentElement.clientHeight-box.offsetHeight;
		});
		console.log(maxLeft+'=2=='+maxTop);
		
		//方法 
		var lval= 2,tval=2;
		function moveDiv(){
			var oldLeft = box.offsetLeft;
			var oldTop = box.offsetTop;
			var newLeft = oldLeft+lval;
			var newTop = oldTop+tval;
			//判断
			if(newLeft>maxLeft){
				newLeft = maxLeft;
			}
			if(newTop>maxTop){
				newTop = maxTop;
			}
			//假如newLeft<0
			if(newLeft<0){
				newLeft = 0;
			}
			if(newTop<0){
				newTop = 0;
			}
			box.style.left = newLeft + 'px';
			box.style.top = newTop + 'px';
			
			if(newLeft==maxLeft||newLeft==0){
				lval = -1*lval;
			}
			if(newTop==maxTop||newTop==0){
				tval = -1*tval;
			}
		}
		//动起来
		var timer = setInterval(moveDiv,10);
			
		//鼠标移入
		box.addEventListener('mouseover',function(e){
			clearInterval(timer);
		});
		//鼠标移出
		box.addEventListener('mouseout',function(e){
			timer = setInterval(moveDiv,10);
		});
		//点X关闭
		closeBtn.addEventListener('click',function(e){
			box.style.display = 'none';
		});
			
	  </script>
</body>
</html>